﻿
namespace SharpDepend.WPF
{
    /// <summary>
    /// Reference: https://msdn.microsoft.com/en-us/library/ms973852.aspx
    /// </summary>
    class StopwatchManager : IStopwatchManager
    {
        private static readonly System.Diagnostics.Stopwatch mStopwatch = new System.Diagnostics.Stopwatch();

        static StopwatchManager()
        {
            mStopwatch.Start();
        }

        public double TickTime
        {
            get
            {
                return mStopwatch.ElapsedMilliseconds;
            }
        }

        class Stopwatch : IStopwatch
        {
            private long lpPerformanceCount;

            [System.Runtime.InteropServices.DllImport("KERNEL32")]
            private static extern bool QueryPerformanceCounter(ref long lpPerformanceCount);

            [System.Runtime.InteropServices.DllImport("KERNEL32")]
            private static extern bool QueryPerformanceFrequency(ref long lpFrequency);

            public double ElapsedTicks { get; private set; }

            public void Start()
            {
                QueryPerformanceCounter(ref lpPerformanceCount);
            }

            public void Stop()
            {
                long lpPerformanceCount2 = 0;
                long lpFrequency = 0;
                QueryPerformanceCounter(ref lpPerformanceCount2);
                QueryPerformanceFrequency(ref lpFrequency);

                ElapsedTicks = ((lpPerformanceCount2 - lpPerformanceCount) * 1.0e9 / lpFrequency) / 1000000000.0;
            }
        }

        public IStopwatch CreateStopwatch()
        {
            return new Stopwatch();
        }
    }
}